package com.scs.application.core.utils;

import com.scs.application.core.exception.BusinessException;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpUrlConnect {
    /**
     * 执行网络请求操作,返回数据会解析成字符串String
     *
     * @param method 请求方式(需要传入String类型的参数:"GET","POST")
     * @param url    请求的url
     * @param params 请求的参数
     * @param token  token
     */
    public static String doHttpReqeust(final String method, final String url, final String params, final String token) throws IOException {
        String result = "";
        HttpURLConnection conn = null;
        OutputStreamWriter out = null;
        BufferedReader in = null;
        try {
            URL http = new URL(url);
            conn = (HttpURLConnection) http.openConnection();
            conn.setReadTimeout(99999999);
            conn.setConnectTimeout(99999999);
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setRequestMethod(method);

            // 设置头部:
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36");
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("X-Token", token);

            // 开始连接请求
            conn.connect();

            // 获取URLConnection对象对应的输出流
            out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
            // 发送请求参数
            out.write(params);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        }catch (IOException e) {
            throw new BusinessException("发送请求出现异常！" + e);
        } finally {
            if (out != null) {
                out.close();
                out = null;
            }
            if (in != null) {
                in.close();
                in = null;
            }
            if(conn !=null) {
                conn.disconnect();
                conn = null;
            }
        }
         return result;
    }
}
